<?php

require_once 'Zend/Filter/Unix/Abstract.php';

class Zend_Filter_Unix_Grep extends Zend_Filter_Unix_Abstract
{
    const UNIT_LINE = 'LINE';
    const UNIT_WORD = 'WORD';
    const UNIT_BYTE = 'BYTE';

    private $_pattern = null;

    private $_invert = null;

    private $_unit = null;

    public function __construct($pattern, $invert = false, $unit = Zend_Filter_Unix_Grep::UNIT_LINE)
    {
        $this->setPattern($pattern);
        $this->setInvert($invert);
        $this->setUnit($unit);
    }

    public function setPattern($pattern)
    {
        $this->_pattern = $pattern;
    }

    public function getPattern($pattern)
    {
        return $this->_pattern;
    }

    public function setInvert($invert)
    {
        $this->_invert = $invert;
    }

    public function getInvert()
    {
        return $this->_invert;
    }

    public function setUnit($unit)
    {
        $this->_unit = strtoupper($unit);
    }

    public function getUnit()
    {
        return $this->_unit;
    }

    public function filter($value)
    {
        switch($this->_unit) {
            case Zend_Filter_Unix_Grep::UNIT_LINE:
                $lines = $this->_parseLines($value);
                if($this->_invert) {
                    $lines = preg_grep($this->_pattern, $lines, PREG_GREP_INVERT);
                } else {
                    $lines = preg_grep($this->_pattern, $lines);
                }

                return implode('', $lines);
            case Zend_Filter_Unix_Grep::UNIT_WORD:
                //TODO: implement
                require_once 'Zend/Filter/Exception.php';

                throw new Zend_Filter_Exception('Unimplemnted');
            case Zend_Filter_Unix_Grep::UNIT_BYTE:
                $bytes = str_split($value);
                //TODO: implement arrays and ints as patterns
                if($this->_invert) {
                    $bytes = preg_grep($this->_pattern, $bytes, PREG_GREP_INVERT);
                } else {
                    $bytes = preg_grep($this->_pattern, $bytes);
                }

                return implode('', $bytes);
        }
    }
}